#!/bin/bash
set -e

source $(dirname $0)/version

cd $(dirname $0)/..

docker buildx build \
  --platform linux/${ARCH} \
  --build-arg REPO=${REPO} \
  --build-arg TAG=${TAG} \
  --build-arg VERSION=${VERSION} \
  --file package/Dockerfile \
  --tag ${REPO}/system-upgrade-controller:${TAG} \
  --tag ${REPO}/system-upgrade-controller:latest \
  --target controller \
.

docker image save --output ./dist/artifacts/system-upgrade-controller-${ARCH}.tar \
  ${REPO}/system-upgrade-controller:${TAG} \
  ${REPO}/system-upgrade-controller:latest
echo ${REPO}/system-upgrade-controller:${TAG} > ./dist/images.txt
echo Built ${REPO}/system-upgrade-controller:${TAG}

reset-kustomization() {
  cp -vf /tmp/kustomization.yaml .
}

if [ "$ARCH" = "amd64" ]; then
  cp kustomization.yaml /tmp/
  trap reset-kustomization EXIT
  kustomize edit set image "rancher/system-upgrade-controller=${REPO}/system-upgrade-controller:${VERSION}"
  kustomize build --output ./dist/artifacts/system-upgrade-controller.yaml
  cat ./pkg/crds/yaml/*/* > dist/artifacts/crd.yaml
fi
